import os
from datetime import datetime
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.db.models import Q
from PetNetadmin.serializers import SellPetSerializer
from rest_framework import status
from utils.pagination import PetMessagePagination
from utils.imageupload import ImageUpload
from admincharge.models import SellPet
from admincharge.utils.jwt import MyJWTAuthentication


class GetAllSellPetMessage(APIView):
    authentication_classes = [MyJWTAuthentication]

    def get(self, request):
        sell_id = request.GET.get('sell_id')
        species = request.GET.get('species')
        sex = request.GET.get('sex')
        price = request.GET.get('price')
        create_time = request.GET.get('create_time')
        # 构建查询条件
        conditions = Q()
        if sell_id:
            conditions &= Q(sell_id=sell_id)
        if species:
            conditions &= Q(species=species)
        if sex:
            conditions &= Q(sex=sex)
        if price:
            conditions &= Q(price=price)
        if create_time:
            conditions &= Q(create_time__contains=create_time)
        # 应用查询条件或返回所有数据
        if conditions:
            queryset = SellPet.objects.filter(conditions)
        else:
            queryset = SellPet.objects.all()
        # 分页处理
        paginator = PetMessagePagination()
        result_page = paginator.paginate_queryset(queryset, request)
        serializer = SellPetSerializer(instance=result_page, many=True)
        result = {
            'data': serializer.data,
            'code': 2000,
            'msg': '获取成功'
        }
        return paginator.get_paginated_response(result)

    def post(self, request):
        get_message = request.data
        print('get_message', get_message)
        serializer = SellPetSerializer(data=get_message, partial=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            result = {
                'code': 2000,
                'msg': '上传保存成功'
            }
            return Response(status=status.HTTP_200_OK, data=result)
        return Response({"msg": '出了点问题噢!!!'}, status=status.HTTP_400_BAD_REQUEST, )


class UploadSellPetImageView(APIView):
    def post(self, request):
        result = ImageUpload(request, 'sell')
        print(result)
        if result['code'] == 2000:
            return Response(data=result['img'])
        else:
            return Response('没有上传成功')


# 删除单个数据
@api_view(['POST'])
def deleteOneSellmsg(request, id):
    try:
        sellMsg = SellPet.objects.get(pk=id)
        imagefile = SellPet.objects.get(pk=id).picture
        print(imagefile)
        sellMsg.delete()
        imagefile = imagefile.split(':8000/')[1]
        print(imagefile)
        if os.path.exists(imagefile):
            os.remove(imagefile)
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except SellPet.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)


# 删除多个数据时
@api_view(['POST'])
def deleteManySellmsg(request):
    try:
        ids = request.data['Ids']
        # 用来保存被删除对象的imgsurl字段
        # deleted_imgsurls = []
        for id in ids:
            pet_message = SellPet.objects.get(id=id)
            imgsurl = pet_message.picture
            imagefile = imgsurl.split(':8000/')[1]
            print(imagefile)
            if os.path.exists(imagefile):
                os.remove(imagefile)
            pet_message.delete()
        # print(deleted_imgsurls)
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except SellPet.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)


@api_view(['POST'])
def editSellMsg(request):
    try:
        id = request.data['id']
        print(request.data)
        new_img_url = request.data['picture']
        old_img_url = SellPet.objects.get(id=id).picture
        if new_img_url != old_img_url:
            print(old_img_url)
            old_img_url = old_img_url.split(':8000/')[1]
            if os.path.exists(old_img_url):
                os.remove(old_img_url)
                print(f'删除成功{old_img_url}')
        updateMsg = SellPet.objects.get(id=id)
        serializer = SellPetSerializer(instance=updateMsg, data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
        result = {
            'code': 2000,
            'msg': '上传保存成功'
        }
        return Response(result)
    except SellPet.DoesNotExist:
        return Response({"msg": '当前没有该记录可以修改'}, status=status.HTTP_404_NOT_FOUND)
